import Dexie, { Table } from "dexie";

// 用户配置接口
export interface UserConfig {
  id?: number;
  userId: string;
  configType: string;
  configData: any;
  createdAt?: Date;
  updatedAt?: Date;
}

// Dexie数据库类
export class JianYingDatabase extends Dexie {
  // 用户配置表
  userConfigs!: Table<UserConfig>;

  constructor() {
    super("JianYingDatabase");

    this.version(1).stores({
      userConfigs: "++id, userId, configType, createdAt, updatedAt",
    });

    // 自动设置时间戳
    this.userConfigs.hook("creating", function (primKey, obj, trans) {
      obj.createdAt = new Date();
      obj.updatedAt = new Date();
    });

    this.userConfigs.hook(
      "updating",
      function (modifications, primKey, obj, trans) {
        (modifications as any).updatedAt = new Date();
      },
    );
  }
}

// 创建数据库实例
export const db = new JianYingDatabase();

// 数据库初始化
export const initDatabase = async () => {
  try {
    await db.open();
    console.log("🗄️ 数据库初始化成功");
    return true;
  } catch (error) {
    console.error("❌ 数据库初始化失败:", error);
    return false;
  }
};

// 保存用户配置
export const saveUserConfig = async (
  userId: string,
  configType: string,
  configData: any,
) => {
  try {
    // 查找是否已存在该用户的该类型配置
    const existing = await db.userConfigs.where({ userId, configType }).first();

    if (existing) {
      // 更新现有配置
      await db.userConfigs.update(existing.id!, { configData });
    } else {
      // 创建新配置
      await db.userConfigs.add({ userId, configType, configData });
    }

    console.log(`✅ 保存用户配置成功: ${userId} - ${configType}`);
    return true;
  } catch (error) {
    console.error("保存用户配置失败:", error);
    return false;
  }
};

// 获取用户配置
export const getUserConfig = async (userId: string, configType: string) => {
  try {
    const config = await db.userConfigs.where({ userId, configType }).first();

    return config?.configData || null;
  } catch (error) {
    console.error("获取用户配置失败:", error);
    return null;
  }
};

// 获取用户所有配置
export const getAllUserConfigs = async (userId: string) => {
  try {
    const configs = await db.userConfigs
      .where("userId")
      .equals(userId)
      .toArray();

    return configs;
  } catch (error) {
    console.error("获取用户所有配置失败:", error);
    return [];
  }
};

// 删除用户配置
export const deleteUserConfig = async (userId: string, configType: string) => {
  try {
    await db.userConfigs.where({ userId, configType }).delete();

    console.log(`🗑️ 删除用户配置成功: ${userId} - ${configType}`);
    return true;
  } catch (error) {
    console.error("删除用户配置失败:", error);
    return false;
  }
};
